package com.woniuxy.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.core.exception.orderException.OrderException;
import com.woniuxy.core.exception.orderException.OrderExceptionCode;
import com.woniuxy.core.staticCode.OrderCode;
import com.woniuxy.order.dao.OrderComment;
import com.woniuxy.order.dao.OrderInfo;
import com.woniuxy.order.mapper.OrderCommentMapper;
import com.woniuxy.order.service.OrderCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.order.service.OrderInfoService;
import com.woniuxy.order.service.param.CommentOrderParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 凌玉春
 * @since 2024年01月15日
 */
@Service
public class OrderCommentServiceImpl extends ServiceImpl<OrderCommentMapper, OrderComment> implements OrderCommentService {
    @Autowired
    private OrderCommentMapper orderCommentMapper;
    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public void commentOrder(CommentOrderParam param) {
        Integer orderId = param.getOrderInfoId();
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo==null){
            throw new OrderException(OrderExceptionCode.ORDER_INEXISTENCE);
        }
        OrderComment orderComment = BeanUtil.toBean(param, OrderComment.class);
        LocalDateTime now = LocalDateTime.now();
        String orderInfoNum = orderInfo.getOrderInfoNum();
        QueryWrapper<OrderComment> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info_num",orderInfoNum);
        Long count = orderCommentMapper.selectCount(wrapper);
        if (count>=1){
            throw new OrderException(OrderExceptionCode.ORDER_HAD_COMMENT);
        }
        orderComment.setOrderInfoNum(orderInfoNum);
        orderComment.setCommentTime(now);
        orderCommentMapper.insert(orderComment);
        orderInfo.setIsComment(OrderCode.ORDER_HAD_COMMENT.getCode());
        orderInfoService.setHadComment(orderInfo);
    }
}
